<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="8em">
      <el-form-item label="公司名称" prop="name">
        <el-input v-model="form.name" placeholder="输入公司名称" />
      </el-form-item>
      <el-form-item label="公司代码" prop="code">
        <el-input v-model="form.code" placeholder="输入公司代码" />
      </el-form-item>
      <el-form-item label="公司类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio v-for="(option, index) in companyTypes" :key="index" :value="option">
            {{ option === "ems" ? "国际邮政" : option === "domestic" ? "国内" : "国际" }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, watch } from "vue";
import { ExpressCompanyForm, ExpressCompanyTypeType } from "@/api/logistics/company";
import { useExpressCompanyStoreHook } from "@/store/modules/logistics/company";

const props = defineProps({
  mode: {
    type: String,
    default: "add",
    validator: (value: string) => ["add", "edit"].includes(value),
  },
  company: {
    type: Object as () => ExpressCompanyForm,
    default: () => ({
      id: undefined,
      name: "",
      code: "",
      type: "international",
      is_active: true,
    }),
  },
});

const expressCompanyStore = useExpressCompanyStoreHook();
const visible = defineModel({ type: Boolean, default: false });
const title = ref("快递公司信息");
const formRef = ref(null);
const form = reactive<ExpressCompanyForm>({
  id: undefined,
  name: "",
  code: "",
  type: "international",
  is_active: true,
});
const rules = reactive({
  name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入公司代码", trigger: "blur" }],
  type: [{ required: true, message: "请选择公司类型", trigger: "change" }],
  is_active: [{ required: true, message: "请选择状态", trigger: "change" }],
});
const companyTypes: ExpressCompanyTypeType[] = ["ems", "domestic", "international"];

watch(
  () => props.company,
  (newCompany) => {
    Object.assign(form, newCompany);
  },
  { immediate: true }
);

const handleSubmit = async () => {
  if (props.mode === "add") {
    await expressCompanyStore.fetchCreate(form);
  } else if (props.mode === "edit") {
    await expressCompanyStore.fetchUpdate(form);
  }
  visible.value = false;
  // 重新获取列表数据
  await expressCompanyStore.fetchList({ page: 1, size: 10 });
};
</script>

<style scoped lang="scss"></style>
